﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// add
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Reflection;

namespace FormBaseLib
{

    public static class CCommon
    {
        public static CBase mLastError = new CBase();
        /// <summary>
        /// get serialized xml text for any class marked as [Serializable()]
        /// </summary>
        public static string SerializeToXMLString<T>(T oFrom)
        {
            using (MemoryStream stream1 = new MemoryStream())
            {
                XmlDocument xmlDoc1 = new XmlDocument();
                XmlSerializer serializer1 = new XmlSerializer(typeof(T));
                serializer1.Serialize(stream1, oFrom);
                stream1.Position = 0;
                xmlDoc1.Load(stream1);
                return xmlDoc1.InnerXml;
            }
        }
        public static string SerializeToUTF8String<T>(T obj)
        {
            // todo: test difference to SerializeToXMLString ?
            //MemoryStream stream1 = new MemoryStream();
            using (MemoryStream stream1 = new MemoryStream())
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                XmlTextWriter xmlTextWriter = new XmlTextWriter(stream1, Encoding.UTF8);

                xmlSerializer.Serialize(xmlTextWriter, obj);
                MemoryStream stream2 = xmlTextWriter.BaseStream as MemoryStream;
                string xmlString = CCommon.ByteArrayToStringUtf8(stream2.ToArray());

                xmlTextWriter.Close();
                return xmlString;
            }
            //stream1.Close();
            //stream1.Dispose();

        }

        public static bool DescrializeFromFile<T>(string sFile, Encoding Encoding1, T oToLoad)
        {
            try
            {
                using (FileStream fstream1 = new FileStream(sFile, FileMode.Open))
                {
                    XmlSerializer xs1 = new XmlSerializer(typeof(T));
                    using (StreamReader sr1 = new StreamReader(fstream1, Encoding1))
                    {
                        oToLoad = (T)xs1.Deserialize(sr1);
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                mLastError.SetLastError(-1, "ERROR: DescrializeFromFile(). " + ex.Message);
                oToLoad = default(T);
                return false;
            }
        }

        public static bool SerializerToFile<T>(string sFile, Encoding Encoding1, T oToSave)
        {
            mLastError.ClearLastError();
            try
            {
                XmlSerializer xs1 = new XmlSerializer(typeof(T));
                using (FileStream fstream1 = new FileStream(sFile, FileMode.Create))
                {
                    XmlTextWriter xw1 = new XmlTextWriter(fstream1, Encoding1);
                    xs1.Serialize(xw1, oToSave);
                }
                return true;
            }
            catch (Exception ex)
            {
                mLastError.SetLastError(-1, "ERROR: SerializerToFile(). " + ex.Message);
                return false;
            }
        }
        /// <summary>
        /// Copy (deep clone copy) any class marked as [Serializable()]
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oFrom"></param>
        /// <returns></returns>
        public static T CopyDeepFromSerializable<T>(T oFrom)
        {
            using (MemoryStream stream1 = new MemoryStream())
            {
                BinaryFormatter bFormatter1 = new BinaryFormatter();
                bFormatter1.Serialize(stream1, oFrom);
                stream1.Position = 0;
                return (T)bFormatter1.Deserialize(stream1);
            }
        }
        /// <summary>
        /// dump xml content for any class marked as [Serializable()]
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oFrom"></param>
        /// <returns></returns>
        public static string DumpSerializableToXML<T>(T oFrom)
        {
            using (MemoryStream stream1 = new MemoryStream())
            {
                XmlDocument xmlDoc1 = new XmlDocument();
                XmlSerializer serializer1 = new XmlSerializer(typeof(T));
                serializer1.Serialize(stream1, oFrom);
                stream1.Position = 0;
                xmlDoc1.Load(stream1);
                return xmlDoc1.InnerXml;
            }
        }
        public static T DeserializeFromUTF8String<T>(string xml)
        {
            using (MemoryStream memoryStream = new MemoryStream(StringToByteArrayUtf8(xml)))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

                using (StreamReader xmlStreamReader = new StreamReader(memoryStream, Encoding.UTF8))
                {
                    return (T)xmlSerializer.Deserialize(xmlStreamReader);
                }
            }
        }
        public static string ByteArrayToStringUtf8(byte[] value)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetString(value);
        }

        public static byte[] StringToByteArrayUtf8(string value)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetBytes(value);
        }
        private static bool IsUTF8Bytes(byte[] data)
        {
            int charByteCounter = 1;
            byte curByte;
            for (int i = 0; i < data.Length; i++)
            {
                curByte = data[i];
                if (charByteCounter == 1)
                {
                    if (curByte >= 0x80)
                    {
                        while (((curByte <<= 1) & 0x80) != 0)
                        {
                            charByteCounter++;
                        }

                        if (charByteCounter == 1 || charByteCounter > 6)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    if ((curByte & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    charByteCounter--;
                }
            }
            if (charByteCounter > 1)
            {
                throw new Exception("Error byte format");
            }
            return true;
        }
        public static Encoding GetEncoding(FileStream fs)
        {
            byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
            byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
            byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //with BOM
            Encoding reVal = Encoding.Default;

            BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
            int i;
            int.TryParse(fs.Length.ToString(), out i);
            byte[] ss = r.ReadBytes(i);
            if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
            {
                reVal = Encoding.UTF8;
            }
            else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
            {
                reVal = Encoding.BigEndianUnicode;
            }
            else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
            {
                reVal = Encoding.Unicode;
            }
            r.Close();
            return reVal;

        }
        public static byte[] StringToByteArray(string sInput, Encoding encoding1)
        {
            // CodeHelper
            return encoding1.GetBytes(sInput);
        }

        public static string ByteArrayToString(byte[] baInput, Encoding encoding1)
        {
            // CodeHelper
            return encoding1.GetString(baInput);
        }

        public static Encoding GetEncoding(string FILE_NAME)
        {
            FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
            Encoding r = GetEncoding(fs);
            fs.Close();
            return r;
        }
        private static T DescrializeFromFile2<T>(string sFile, Encoding Encoding1, T oToLoad)
        {
            try
            {

                using (FileStream fstream1 = new FileStream(sFile, FileMode.Open))
                {
                    XmlSerializer xs1 = new XmlSerializer(typeof(T));
                    using (StreamReader sr1 = new StreamReader(fstream1, Encoding1))
                    {
                        return (T)xs1.Deserialize(sr1);
                    }
                }
            }
            catch (Exception ex)
            {
                //mError.SetError(ex, "DescrializeFromFile");
                mLastError.SetLastError(-1, "ERROR:" + ex.Message);
                //return null;
                return default(T);
            }
        }
        public static string gGetPhysicalFilename(long lFileno)
        {
            // return mapped file storage path for (file based upload/download file system)
            // Signed 64-bit integer
            // System.Int64
            // –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

            // file system in tree structure: 
            // 1. tree height = 6.
            // 2. 100 children in each node for the performance concern in Windows file system environment.

            // 1   2     3        4           5             6                7
            //     百    萬       百萬        億            百億
            // 1 - 100 - 10,000 - 1,000,000 - 100,000,000 - 10,000,000,000 - 再大的話同一顆硬碟也放不下了!
            //                                             990,000,000,000
            //                                           1,000,000,000,000
            // dividend over divisor = quotient + remainder
            string s1;
            s1 = (100000000000000L + lFileno).ToString();
            string sFilename = s1.Substring(1, 2)
                + "\\" + s1.Substring(3, 2)
                + "\\" + s1.Substring(5, 2)
                + "\\" + s1.Substring(7, 2)
                + "\\" + s1.Substring(9, 2)
                + "\\" + s1.Substring(11, 2)
                + "\\" + lFileno.ToString();
            return sFilename;

        }
        public static void gSleep(Int32 iMilliseconds)
        {
            // code helper
            Thread.Sleep(iMilliseconds);
        }
        private static bool CopyDataRows(DataRow rFrom, DataRow rTo)
        {
            // CodeHelper:
            rTo.ItemArray = rFrom.ItemArray.Clone() as object[];
            return true;
        }
        private static void SaveXML(DataSet ds, string sFile)
        {
            File.WriteAllText(sFile, ds.GetXml(), Encoding.UTF8);
        }
        private static void SaveXMLSchema(DataSet ds, string sFile)
        {
            File.WriteAllText(sFile, ds.GetXmlSchema().Replace("utf-16", "utf-8"), Encoding.UTF8);
        }
        public static Form gShowForm(Type typeofForm)
        {
            Form fOpen = gGetOpenForm(typeofForm);
            Form fNew = null;
            if (fOpen == null)
                fNew = (Form)CreateNewInstanceOfType(typeofForm);
            else
                if (fOpen.IsDisposed)
                    fNew = (Form)CreateNewInstanceOfType(typeofForm);
                else
                    fNew = fOpen;

            fNew.Show();
            fNew.Focus();
            return fNew;
        }
        public static Form gShowFormFixedSingle(Type typeofForm, string sCaption, Form fMDIParent)
        {
            //DebugMsg("ShowForm() " + typeofForm.Name);
            Form fOpen = gGetOpenForm(typeofForm);
            Form fNew = null;
            //if (fNew == null)
            //    fNew = (Form)CreateNewInstanceOfType(typeofForm);
            //else
            //    if (fNew.IsDisposed)
            //        fNew = (Form)CreateNewInstanceOfType(typeofForm);

            if (fOpen == null)
                fNew = (Form)CreateNewInstanceOfType(typeofForm);
            else
                if (fOpen.IsDisposed)
                    fNew = (Form)CreateNewInstanceOfType(typeofForm);
                else
                    fNew = fOpen;

            if (fOpen == null) // new instance first time!
            {
                if (!string.IsNullOrEmpty(sCaption))
                    fNew.Text = sCaption;

                fNew.ControlBox = true;
                fNew.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                fNew.MaximizeBox = false;
                fNew.MinimizeBox = false;
                if (fMDIParent != null)
                    if (fNew.MdiParent == null)
                        fNew.MdiParent = fMDIParent;
                //fNew.StartPosition = FormStartPosition.Manual;
                //fNew.Left = 0;
                //fNew.Top = 0;
                fNew.StartPosition = FormStartPosition.CenterScreen;
            }
            fNew.Show();
            fNew.Focus();
            return fNew;
        }
        public static Form gShowFormMDIChild(Type typeofForm, string sCaption, Form fMDIParent)
        {
            //DebugMsg("ShowForm() " + typeofForm.Name);
            Form fOpen = gGetOpenForm(typeofForm);
            Form fNew = null;
            //if (fNew == null)
            //    fNew = (Form)CreateNewInstanceOfType(typeofForm);
            //else
            //    if (fNew.IsDisposed)
            //        fNew = (Form)CreateNewInstanceOfType(typeofForm);

            if (fOpen == null)
                fNew = (Form)CreateNewInstanceOfType(typeofForm);
            else
                if (fOpen.IsDisposed)
                    fNew = (Form)CreateNewInstanceOfType(typeofForm);
                else
                    fNew = fOpen;

            if (fOpen == null) // new instance first time!
            {
                if (!string.IsNullOrEmpty(sCaption))
                    fNew.Text = sCaption;

                //fNew.ControlBox = true;
                //fNew.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                //fNew.MaximizeBox = false;
                //fNew.MinimizeBox = false;
                if (fMDIParent != null)
                    if (fNew.MdiParent == null)
                        fNew.MdiParent = fMDIParent;
                //fNew.StartPosition = FormStartPosition.Manual;
                //fNew.Left = 0;
                //fNew.Top = 0;
                fNew.StartPosition = FormStartPosition.CenterScreen;
            }
            fNew.Show();
            fNew.Focus();
            return fNew;
        }

        public static Form gShowForm(Type typeofForm, string sCaption, Form fMDIParent)
        {
            //DebugMsg("ShowForm() " + typeofForm.Name);
            Form fOpen = gGetOpenForm(typeofForm);
            Form fNew = null;
            //if (fNew == null)
            //    fNew = (Form)CreateNewInstanceOfType(typeofForm);
            //else
            //    if (fNew.IsDisposed)
            //        fNew = (Form)CreateNewInstanceOfType(typeofForm);

            if (fOpen == null)
                fNew = (Form)CreateNewInstanceOfType(typeofForm);
            else
                if (fOpen.IsDisposed)
                    fNew = (Form)CreateNewInstanceOfType(typeofForm);
                else
                    fNew = fOpen;

            if (fOpen == null) // new instance first time!
            {
                if (!string.IsNullOrEmpty(sCaption))
                    fNew.Text = sCaption;

                //fNew.ControlBox = true;
                //fNew.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                //fNew.MaximizeBox = false;
                //fNew.MinimizeBox = false;
                if (fMDIParent != null)
                    if (fNew.MdiParent == null)
                        fNew.MdiParent = fMDIParent;
                //fNew.StartPosition = FormStartPosition.Manual;
                //fNew.Left = 0;
                //fNew.Top = 0;
                fNew.StartPosition = FormStartPosition.CenterScreen;
            }
            fNew.Show();
            fNew.Focus();
            return fNew;
        }
        public static Form gGetOpenForm(Type typeofForm)
        {
            FormCollection fc = Application.OpenForms;
            foreach (Form f1 in fc)
                if (f1.GetType() == typeofForm)
                    return f1;

            return null;
        }
        public static object CreateNewInstanceOfType(Type typeofAny)
        {
            return Activator.CreateInstance(typeofAny);
        }
        public static string gBytesToStringUTF8(byte[] baInput)
        {
            return System.Text.Encoding.UTF8.GetString(baInput);
        }
        public static string gByteArrayToHex(byte[] baInput)
        {
            // code helper:
            // byte[] data = { 1, 2, 4, 8, 16, 32 };
            // string hex = BitConverter.ToString(data);
            // hex = 01-02-04-08-10-20
            // string hex = BitConverter.ToString(data).Replace("-", string.Empty);
            // hex = 010204081020
            //return BitConverter.ToString(ba1).Replace("-", string.Empty);
            return BitConverter.ToString(baInput);
        }
        public static string gStringToHex(string sInput)
        {
            return BitConverter.ToString(gStringToBytes(sInput));
        }
        public static string gStringASCToHex(string sInput)
        {
            return gByteArrayToHex(gStringUTF8ToBytes(sInput));
        }

        public static byte[] gStringToBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }
        public static byte[] gStringUTF8ToBytes(string sUTF8)
        {
            return (System.Text.Encoding.UTF8.GetBytes(sUTF8));
        }

        public static string gBytesToString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }
        public static string AssemblyTitle
        {
            get
            {
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
                if (attributes.Length > 0)
                {
                    AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
                    if (titleAttribute.Title != "")
                    {
                        return titleAttribute.Title;
                    }
                }
                return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
            }
        }

        //public static string AssemblyVersion
        //{
        //    get
        //    {
        //        return Assembly.GetExecutingAssembly().GetName().Version.ToString();
        //    }
        //}
        public static string gCRLFForceTo(string sInput)
        {
            return gCRLFReplace(sInput, "\r\n");
        }
        public static string gCRLFRemove(string sInput)
        {
            return gCRLFReplace(sInput, string.Empty);
        }
        public static string gCRLFReplace(string sInput, string sToReplace)
        {
            return sInput.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", sToReplace);
        }
        public static void gCboSetIndex(ComboBox cbo, string sInput)
        {
            int iIndex = 0;

            iIndex = cbo.Items.IndexOf(sInput);
            if (iIndex < 0)
                cbo.SelectedText = string.Empty; // 不要設成sinput, 導致誤解cbo.SelectedValue!

            cbo.SelectedIndex = iIndex;
        }
        public static int gCboGetIndex(ComboBox cbo, string sInput)
        {
            return cbo.Items.IndexOf(sInput);
        }
        public static int gCboGetIndex(ComboBox cbo, int iInput)
        {
            // 注意: items = ObjectCollection, 因此可存取數值...等非字串值陣列. (建議特殊情況才用, 因容易混淆!)
            return cbo.Items.IndexOf(iInput);
        }
        public static bool gGetEnumItem(Type TypeOfEnum1, string sItem, out object oEnumItem)
        {
            oEnumItem = null;
            if (string.IsNullOrEmpty(sItem))
                return false;

            if (!Enum.IsDefined(TypeOfEnum1, sItem))
                return false;

            oEnumItem = Enum.Parse(TypeOfEnum1, sItem);
            return true;
        }
        public static bool gGetEnumItem(Type TypeOfEnum1, int iInput, out object oEnumItem)
        {
            oEnumItem = null;

            if (!Enum.IsDefined(TypeOfEnum1, iInput))
                return false;

            oEnumItem = iInput;
            return true;
        }
        public static void gCboAddItem(ComboBox cbo, Type typeofEnum, bool bByName)
        {
            if (bByName)
            {
                foreach (string s in Enum.GetNames(typeofEnum))
                    cbo.Items.Add(s);
            }
            else
            {
                // keep in string format!
                foreach (int i in Enum.GetValues(typeofEnum))
                    cbo.Items.Add(i.ToString());
            }

        }
        static public string[] gSplitLeftRight(this string sInput, string sDelimiter)
        {
            if (string.IsNullOrEmpty(sInput))
                return new string[] { string.Empty, string.Empty };

            if (string.IsNullOrEmpty(sDelimiter))
                return new string[] { sInput, string.Empty };

            return sInput.Split(new string[] { sDelimiter }, 2, StringSplitOptions.None);
        }

    }
}
